﻿using MediatR;
using TaskProject.Application.Command.BOM;
using TaskProject.Domain.BOM;
using TaskProject.ErrorCode;
using TaskProject.InfrasIntructure.Implement;
using TaskProject.InfrasIntructure.Interface;

namespace TaskProject.Application.Handler.BOM
{
    public class DelBOMHandler : IRequestHandler<DelBOMCommand, APIResult<int>>
    {
        IBaseRepository<BOMModel> bomRepo;
        DatabaseContext db;

        public DelBOMHandler(IBaseRepository<BOMModel> bomRepo, DatabaseContext db)
        {
            this.bomRepo = bomRepo;
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(DelBOMCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();

            
            var existingBOM = bomRepo.GetAll().Where(c => c.BOMId == request.BOMId).FirstOrDefault();

            if (existingBOM == null)
            {
                res.Msg = "BOMId找不到";
                res.Code = APIEnum.Fail;
                return res;
            }
            //SetColumns是只更改指定的字段 ExecuteCommandAsync 是异步执行更新并返回受影响的行数

            int affectedRows = await db.sqlSugar.Updateable<BOMModel>().SetColumns(c => new BOMModel { 
                IsDel = true,
                CreteName = "王五",
                CreteDate = DateTime.Now,
                CreateDesc = "王五删除了一条数据"
            }).Where(c => c.BOMId == request.BOMId).ExecuteCommandAsync();

            if (affectedRows > 0)
            {
                res.Msg = "删除成功";
                res.Code = APIEnum.Success;
                res.Data = affectedRows;
            }
            else
            {
                res.Msg = "删除失败";
                res.Code = APIEnum.Fail;
                res.Data = affectedRows;
            }

            return res;
        }
    }
}
